using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using ElectronicMallProject.Backend.Api.Entity;
using ElectronicMallProject.Backend.Api.Repository;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using ElectronicMallProject.Backend.Api.Params;
using ElectronicMallProject.Backend.Api.Database;
using Microsoft.AspNetCore.Hosting;
using System;

//商品控制器
namespace ElectronicMallProject.Backend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class CommodityController : ControllerBase
    {
        private readonly DbInit _context;
        //图片
        private IRepository<Imgs> _imgRepository;
        //商品
        private IRepository<Commodity> _commodityRepository;
        //类型
        private IRepository<ShopType> _shoptypeRepository;
        //品牌
        private IRepository<Brand> _brandRepository;
        //规格
        private IRepository<Specifications> _specificationsRepository;
        //商品相册表
        private IRepository<DetailsChart> _detailsChartRepository;
        private IConfiguration _configuration;

        public CommodityController(IRepository<DetailsChart> detailsChartRepository, IRepository<Imgs> imgRepository, IRepository<Commodity> commodityRepository, IRepository<ShopType> shoptypeRepository,
        IRepository<Brand> brandRepository, IRepository<Specifications> specificationsRepository, IConfiguration configuration, IWebHostEnvironment iWebHostEnvironment)
        {
            _context = new DbInit();
            _imgRepository = imgRepository;
            _commodityRepository = commodityRepository;
            _shoptypeRepository = shoptypeRepository;
            _brandRepository = brandRepository;
            _specificationsRepository = specificationsRepository;
            _configuration = configuration;
            _detailsChartRepository = detailsChartRepository;

        }

        [HttpGet, Route("getcom")]
        public dynamic comGet()
        {
            var commodity = _commodityRepository.Table;

            return new
            {
                Code = 200,
                Data = commodity,
                Msg = "查询所有商品成功"
            };
        }

        //查询所有商品
        [HttpGet]
        public dynamic Get()
        {
            var commodity = _commodityRepository.Table.ToList();

            ArrayList list = new ArrayList();

            foreach (var item in commodity)
            {
                var imgpath = _imgRepository.Table.Where(x => x.Id == item.ImgId).FirstOrDefault();

                var brandid = _brandRepository.Table.Where(x => x.Id == item.BrandId).FirstOrDefault();

                var specifications = _specificationsRepository.Table.Where(x => x.CommodityId == item.Id).ToList();

                var res = new
                {
                    Id = item.Id,
                    isActived = item.IsActived,
                    isDeleted = item.IsDeleted,
                    createdTime = item.CreatedTime,
                    updatedTime = item.UpdatedTime,
                    displayOrder = item.DisplayOrder,
                    remarks = item.Remarks,
                    CommodityName = item.CommodityName,
                    CommodityCurrentPrice = item.CommodityCurrentPrice,
                    SpecificationsId = item.SpecificationsId,
                    ProductDetails = item.ProductDetails,
                    ProductStocks = item.ProductStocks,
                    SupplierId = item.SupplierId,
                    ShopTypeId = item.ShopTypeId,
                    imgpath = imgpath.ImgsPath,
                    brandname = brandid.BrandName,
                    specifications = specifications
                };
                list.Add(res);
            }


            return new
            {
                Code = 200,
                Data = list,
                Msg = "查询所有商品成功"
            };
        }


        // [HttpGet("{id}")]
        // public dynamic GetComName(int id)
        // {

        //     ArrayList list = new ArrayList();
        // }


        //添加商品
        [HttpPost, Route("Addcommodity")]
        public dynamic AddPost(CreateCommodity create)
        {
            var commodityname = create.CommodityName.Trim();
            var commoditycurrentprice = create.CommodityCurrentPrice;
            var productdetails = create.ProductDetails.Trim();
            var imgid = create.ImgId;
            var brandid = create.BrandId;
            var shoptypeid = create.ShopTypeId;



            var res = new Commodity
            {
                CommodityName = commodityname,
                CommodityCurrentPrice = commoditycurrentprice,
                ProductDetails = productdetails,
                ImgId = imgid,
                BrandId = brandid,
                ShopTypeId = shoptypeid
            };

            _commodityRepository.Insert(res);

            return new
            {
                Code = 200,
                Data = res,
                Msg = "添加商品成功"
            };

        }

        //商品相册
        [HttpPost, Route("Commodityimgs")]
        public dynamic commodityimgs(Commodityimgs Commodityimg)
        {
            var ImgId = Commodityimg.ImgId;
            var CommodityId = Commodityimg.CommodityId;

            var res = new DetailsChart
            {
                ImgId = ImgId,
                CommodityId = CommodityId
            };
            _detailsChartRepository.Insert(res);
            return new
            {
                code = 200,
                data = res,
                msg = "添加成功"
            };
        }

        //添加规格
        [HttpPost, Route("Specifications")]
        public dynamic CommoditySpecifications(CommoditySpecifications commoditySpecification)
        {

            var CommodityId = commoditySpecification.CommodityId;
            var SpecificationName = commoditySpecification.SpecificationsName.Trim();
            var price = commoditySpecification.Price;

            var res = new Specifications
            {
                CommodityId = CommodityId,
                SpecificationsName = SpecificationName,
                price = price
            };
            _specificationsRepository.Insert(res);
            return new
            {
                code = 200,
                data = res,
                msg = "规格添加成功"
            };
        }

        //通过商品id查找商品
        [HttpGet, Route("{id}/getCommodityById")]
        public dynamic GetCommodityById(int id)
        {

            var Commodity = _commodityRepository.Table.Where(x => x.Id == id).FirstOrDefault();
            var Specifications = _specificationsRepository.Table.Where(x => x.CommodityId == id).ToList();
            var imgs = _imgRepository.Table;
            var imgPaht = imgs.Where(x => x.Id == Commodity.ImgId).FirstOrDefault().ImgsPath;
            var detailsCharts = _detailsChartRepository.Table.Where(x => x.CommodityId == id).ToList();
            var shoptypeName = _shoptypeRepository.Table.Where(x => x.Id == Commodity.ShopTypeId).FirstOrDefault();
            var brand = _brandRepository.Table.Where(x =>x.Id == Commodity.BrandId).FirstOrDefault();
            ArrayList detailsChart = new ArrayList();
            foreach (var item in detailsCharts)
            {
                var img = imgs.Where(x => x.Id == item.ImgId).FirstOrDefault();
                var res = new
                {
                    imgPaht = img.ImgsPath,
                    imgId = img.Id,
                    id = item.Id
                };
                detailsChart.Add(res);
            }

            var CommodityDetails = new
            {
                CommodityName = Commodity.CommodityName,
                ProductDetails = Commodity.ProductDetails,
                IsActived = Commodity.IsActived,
                IsDeleted = Commodity.IsDeleted,
                Specifications = Specifications,
                imgPaht = imgPaht,
                imgId = Commodity.ImgId,
                detailsChart = detailsChart,
                CreatedTime = Commodity.CreatedTime,
                CommodityCurrentPrice = Commodity.CommodityCurrentPrice,
                Brand = brand,
                shoptypeName = shoptypeName
            };


            return new
            {
                code = 200,
                data = CommodityDetails,
                msg = "查找到对应商品"
            };
        }
        //通过商品id修改商品
        [HttpPost, Route("{id}/updataCommodityById")]
        public dynamic UpdataCommodityById(int id, CreateCommodity create)
        {

            var CommodityName = create.CommodityName.Trim();
            var CommodityCurrentPrice = create.CommodityCurrentPrice;
            var ProductDetails = create.ProductDetails.Trim();
            var ImgId = create.ImgId;
            var BrandId = create.BrandId;
            var ShopTypeId = create.ShopTypeId;

            var commodity = _commodityRepository.GetById(id);

            commodity.CommodityName = CommodityName;
            commodity.CommodityCurrentPrice = CommodityCurrentPrice;
            commodity.ProductDetails = ProductDetails;
            commodity.ImgId = ImgId;
            commodity.BrandId = BrandId;
            commodity.ShopTypeId = ShopTypeId;
            _commodityRepository.Updated(commodity);


            return new
            {
                code = 200,
                data = commodity,
                msg = "修改成功"
            };
        }

        //修改商品相册
        [HttpPost, Route("{id}/updataCommodityimgs")]
        public dynamic Updatacommodityimgs(int id, Commodityimgs Commodityimg)
        {

            var detailsChart = _detailsChartRepository.GetById(id);
            var ImgId = Commodityimg.ImgId;
            var CommodityId = Commodityimg.CommodityId;

            if (detailsChart != null)
            {
                detailsChart.ImgId = ImgId;
                detailsChart.CommodityId = CommodityId;
                _detailsChartRepository.Updated(detailsChart);
            }

            return new
            {
                code = 200,
                data = detailsChart,
                msg = "修改成功"
            };
        }

        //修改商品规格
         [HttpPost, Route("{id}/UpdataSpecifications")]
        public dynamic UpdataCommoditySpecifications(int id ,CommoditySpecifications commoditySpecification)
        {

            var CommodityId = commoditySpecification.CommodityId;
            var SpecificationName = commoditySpecification.SpecificationsName.Trim();
            var price = commoditySpecification.Price;
            var Specification = _specificationsRepository.GetById(id);
           
            Specification.CommodityId = CommodityId;
            Specification.SpecificationsName = SpecificationName;
            Specification.price = price;

            _specificationsRepository.Updated(Specification);

            return new
            {
                code = 200,
                data = Specification,
                msg = "规格修改成功"
            };
        }



        //卖出商品减库存
        [HttpPut, Route("{id}/reducestock")]
        public dynamic ReducePut(int id, CreateCommodity commodity)
        {
            var commodityname = commodity.CommodityName.Trim();
            var commodityquantity = commodity.ProductStocks;

            if (!string.IsNullOrEmpty(commodityname) && !string.IsNullOrEmpty(commodityquantity.ToString()))
            {
                var reducestock = _commodityRepository.GetById(id);

                if (reducestock == null)
                {
                    return new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "出库商品不存在"
                    };
                }

                reducestock.ProductStocks = reducestock.ProductStocks - commodity.ProductStocks;

                _commodityRepository.Updated(reducestock);

                return new
                {
                    Code = 200,
                    Data = reducestock,
                    Msg = "商品出库成功"
                };
            }
            return "";
        }


        //修改商品
        [HttpPut, Route("{id}/Updatecommodity")]
        public dynamic UpdatePut(int id, CreateCommodity commodity)
        {
            var commodityname = commodity.CommodityName.Trim();
            var commoditytype = commodity.CommodityType.Trim();
            var commoditycurrentprice = commodity.CommodityCurrentPrice;
            var specificationsid = commodity.SpecificationsId;
            var productdetails = commodity.ProductDetails.Trim();
            var productstocks = commodity.ProductStocks;
            var imgid = commodity.ImgId;
            var supplierid = commodity.SupplierId;
            var brandid = commodity.BrandId;
            var shoptypeid = commodity.ShopTypeId;

            if (!string.IsNullOrEmpty(commodityname) && !string.IsNullOrEmpty(commoditytype) &&
            !string.IsNullOrEmpty(commoditycurrentprice.ToString()) && !string.IsNullOrEmpty(specificationsid.ToString()) &&
             !string.IsNullOrEmpty(productdetails) && !string.IsNullOrEmpty(productstocks.ToString()) &&
             !string.IsNullOrEmpty(imgid.ToString()) && !string.IsNullOrEmpty(supplierid.ToString()) &&
             !string.IsNullOrEmpty(brandid.ToString()) && !string.IsNullOrEmpty(shoptypeid.ToString()))
            {
                var updatecommodity = _commodityRepository.GetById(id);

                if (updatecommodity == null)
                {
                    return new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "修改商品不存在"
                    };
                }

                updatecommodity.CommodityName = commodity.CommodityName;
                updatecommodity.CommodityType = commodity.CommodityType;
                updatecommodity.CommodityCurrentPrice = commodity.CommodityCurrentPrice;
                updatecommodity.SpecificationsId = commodity.SpecificationsId;
                updatecommodity.ProductDetails = commodity.ProductDetails;
                updatecommodity.ProductStocks = commodity.ProductStocks;
                updatecommodity.ImgId = commodity.ImgId;
                updatecommodity.SupplierId = commodity.SupplierId;
                updatecommodity.BrandId = commodity.BrandId;
                updatecommodity.ShopTypeId = commodity.ShopTypeId;

                _commodityRepository.Updated(updatecommodity);

                return new
                {
                    Code = 200,
                    Data = updatecommodity,
                    Msg = "修改商品成功"
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "修改商品失败"
                };
            }
        }


        //冻结商品
        [HttpPut, Route("{id}/frozencommodity")]
        public dynamic frozenPut(int id)
        {
            var frozencommodity = _commodityRepository.GetById(id);

            if (frozencommodity == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该商品不存在"
                };
            }
            frozencommodity.IsActived = false;
            _commodityRepository.Updated(frozencommodity);

            return new
            {
                Code = 200,
                Data = frozencommodity,
                Msg = "冻结商品成功"
            };
        }

        //启用商品
        [HttpPut, Route("{id}/enablecommodity")]
        public dynamic enablePut(int id)
        {
            var enablecommodity = _commodityRepository.GetById(id);

            if (enablecommodity == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "该商品不存在"
                };
            }
            enablecommodity.IsActived = true;
            _commodityRepository.Updated(enablecommodity);

            return new
            {
                Code = 200,
                Data = enablecommodity,
                Msg = "启用商品成功"
            };
        }


        //查看商品表和图片
        [HttpGet, Route("CommodityImgGet")]
        public dynamic imgGet()
        {
            var commodity = _commodityRepository.Table.ToList();

            ArrayList list = new ArrayList();

            foreach (var item in commodity)
            {
                var img = _imgRepository.Table.Where(x => x.Id == item.ImgId).FirstOrDefault();

                var res = new
                {
                    CommodityName = item.CommodityName,
                    CommodityType = item.CommodityType,
                    CommodityCurrentPrice = item.CommodityCurrentPrice,
                    SpecificationsId = item.SpecificationsId,
                    ProductDetails = item.ProductDetails,
                    ProductStocks = item.ProductStocks,
                    ImgId = item.ImgId,
                    SupplierId = item.SupplierId,
                    BrandId = item.BrandId,
                    ShopTypeId = item.ShopTypeId,
                    imgPath = img.ImgsPath
                };
                list.Add(res);
            }
            return new
            {
                Code = 200,
                Data = list,
                Msg = "查询成功"
            };
        }


        //查看商品所有分类具体到型号
        [HttpGet, Route("{id}")]
        public dynamic seeGet(int id)
        {
            var commoditys = _commodityRepository.Table;
            //商品中含有该品牌
            // var brand = commodity.Where(x => x.BrandId == id).ToList();
            //商品中含有该规格
            // var specifications = commoditys.Where(x =>x.SpecificationsId == id).ToList();

            //对应商品
            var commodity = commoditys.Where(x => x.Id == id).FirstOrDefault();
            //商品类型表
            var shoptypes = _shoptypeRepository.Table;
            //品牌表
            var brands = _brandRepository.Table;
            //规格表
            var specifications = _specificationsRepository.Table;


            //对应商品类型 
            var shoptype = shoptypes.Where(x => x.Id == commodity.ShopTypeId).FirstOrDefault();
            //对应品牌
            var brand = brands.Where(x => x.Id == commodity.BrandId).FirstOrDefault();
            //对应规格 
            var specification = specifications.Where(x => x.Id == commodity.SpecificationsId).FirstOrDefault();




            return new
            {
                Code = 200,
                Data = new { shoptype = shoptype, brand = brand, specification = specification },
                Msg = "查询成功"
            };

        }
        public class queryRes
            {
                public int Id {get;set;}
                public string CommodityName {get;set;}
                public string ProductDetails {get;set;}
                public bool IsActived {get;set;}
                public bool IsDeleted {get;set;}
                public string imgPaht {get;set;}
                public int imgId {get;set;}
                public DateTime CreatedTime {get;set;}
                public int CommodityCurrentPrice {get;set;}
                public string shoptypeName {get;set;}

            }

        //查询商品(可模糊查询)
        [HttpPost, Route("query")]
        public dynamic QueryQuery(Myquery query)
        {
            var queryData = query.queryData != null ? query.queryData : "";
            

            var commoditys = _commodityRepository.Table.ToList();
            var brands = _brandRepository.Table.ToList();
            
            List<queryRes> list = new List<queryRes>();
            foreach (var item in commoditys)
            {
                var brand = brands.Where(x => x.Id == item.BrandId).FirstOrDefault();
                var imgs = _imgRepository.Table;
                var imgPaht = imgs.Where(x => x.Id == item.ImgId).FirstOrDefault().ImgsPath;
                var detailsCharts = _detailsChartRepository.Table.Where(x => x.CommodityId == item.Id).ToList();
                var shoptypeName = _shoptypeRepository.Table.Where(x => x.Id == item.ShopTypeId).FirstOrDefault().ShopTypeName;

                var res = new queryRes
                {
                    Id = item.Id,
                    CommodityName = item.CommodityName,
                    ProductDetails = item.ProductDetails,
                    IsActived = item.IsActived,
                    IsDeleted = item.IsDeleted,
                    imgPaht = imgPaht,
                    imgId = item.ImgId,
                    CreatedTime = item.CreatedTime,
                    CommodityCurrentPrice = item.CommodityCurrentPrice,
                    shoptypeName = shoptypeName
                };

                list.Add(res);
            }
            
            var resData = list.Where(x =>x.CommodityName.Contains(queryData)
             || x.shoptypeName.Contains(queryData)).ToList();

            return new
            {
                code = 200,
                data = resData,
                msg = "查询成功"
            };

        }
    }
}